AsyncFunction

✒️ 2025-05-23 15:25 내용 수정


Javascript의 비동기 함수의 메소드를 제공하는 내장 객체로, Function의 서브 클래스

참고 자료 : mdn web docs async function, mdn web docs AsyncFunction

async function fnName(parameter) {
	// 함수 내용
	await otherFn(); // await 식
}
// Promise 객체를 반환하는 함수 생성
function fetchData(success = true) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			if (success) {
				resolve("데이터 가져오기 성공!");
			} else {
				reject("데이터 가져오기 실패");
			}
		}, 2000); // 2초 후에 실행
	});
}
// Promise의 then() / catch() 사용 시
fetchData(true)
	.then((result) => {
		console.log("성공:", result);
	})
	.catch((error) => {
		console.log("에러:", error);
	});
// async function으로 사용 시
// 비동기 함수 설정
async function fetchTest() {
	try {
		const result = await fetchData(true); // success = true
		console.log("Success : ", result);
	} catch (error) {
		console.error("Error : ", error);
	}
}

// 데이터 처리 시작
fetchTest();

setTimeout

참고 자료 : mdn web docs setTimeout

setTimeout(code);
setTimeout(code, delay);
setTimeout(function(), delay);

// 1초 뒤에 동작
const timer = setTimeout(function() {}, 1000);

// 타이머 취소
clearTimeout(timer);
console.log('3초 딜레이')
const countdonwn = setTimeout(function() {
    console.log('딜레이 종료');
}, 3000);

setInterval

참고 자료 : mdn web docs setInterval

setInterval(code);
setInterval(codd, delay);
setInterval(function(), delay);

// 1초 간격으로 반복
const timer = setInterval(function() {}, 1000);

// 반복 취소
clearInterval(timer);
let count = 5;

const countDown = setInterval(()=>{
    console.log(count);
    if (count > 0) {
        count--;
    } else {
        clearInterval(countDown);
    }
}, 1000);